<script setup lang="ts">
import headerBar from '@/components/headerBar.vue'
import showVideoListBox from '@/components/showVideoListBox.vue'
import footBar from '@/components/footBar.vue'
import { useRoute, useRouter } from 'vue-router'
import * as video from '@/apis/video'
import { ref, type Ref, reactive, watchEffect, watch, onMounted, onUnmounted } from 'vue'
import { ArrowRightBold, ArrowLeftBold, CloseBold } from '@element-plus/icons-vue'
import { useTransition, useElementSize } from '@vueuse/core'
import { useWatchHistry, type typeWatchHistry } from '@/store/watchHistry'
import commentVue from '@/components/comment.vue'

import Player from 'xgplayer'
import 'xgplayer/dist/index.min.css'
import HlsPlayer from 'xgplayer-hls'
let dp: any = null
let lastHistry: any = {}

const watchHistry = useWatchHistry()
const route = useRoute()
const router = useRouter()
const vod_id: number = parseInt(route.params.vod_id as string)
const episode = ref(parseInt((route.query?.episode as string) || '0'))
const vod_id_ = ref(vod_id)
if (episode.value <= 0) episode.value = 0

watch(
  () => route.query?.episode,
  e => {
    episode.value = parseInt(e as string)
    playVideo(videoInfo.value.vod_play_url[episode.value]?.url)
  }
)
const videoPushList: Ref<any[]> = ref([])
const videoInfo: Ref<any> = ref()
video.getList(1, 0, { vod_id }).then(res => {
  res.data = res.data.data
  if (res.data.count == 0) {
    window.location.href = '/404'
  }

  let v = res.data.list[0]
  v.vod_play_url = JSON.parse(v.vod_play_url)
  videoInfo.value = v
  allCount.value = videoInfo.value.vod_play_url.length
  video.getList(20, 0, { searchSame: videoInfo.value.vod_pubdate, vod_id: vod_id, type_id: videoInfo.value.type_id }).then(res => {
    videoPushList.value = res.data.data.list
  })

  if (watchHistry.list[vod_id]?.episode && episode.value == 0) {
    router.push(`/play/${vod_id}?episode=${watchHistry.list[vod_id]?.episode}`)
    return
  }

  playVideo(videoInfo.value.vod_play_url[episode.value]?.url)
  changePage(0)
})

function playVideo(url: string) {
  if (dp) dp.destroy(false)
  dp = new Player({
    el: document.getElementById('video') as HTMLElement,
    plugins: [HlsPlayer],
    height: '100%',
    width: '100%',
    videoInit: true,
    url: url,
    pip: true,
    volume: 1,
    lang: 'zh-cn',
    cssFullscreen: false,
    autoplay: true
  })

  dp.on('canplaythrough', function () {
    dp.play()
  })
  dp.on('ended', () => {
    let nextIndex = episode.value + 1
    if (nextIndex >= videoInfo.value.vod_play_url.length) return
    router.push(`/play/${vod_id_.value}?episode=${nextIndex}`)
  })
  dp.on('play', () => {
    if (watchHistry.list[vod_id]?.currentTime) {
      if (watchHistry.list[vod_id]?.episode != episode.value) return
      lastHistry = watchHistry.list[vod_id]
      let ct = watchHistry.list[vod_id]?.currentTime
      if (!ct || ct < 5) return
      if (Math.abs(ct - dp.video.currentTime) > 5) dp.seek(watchHistry.list[vod_id]?.currentTime)
    }
  })
  dp.on('timeupdate', () => {
    if (!dp.duration || !dp.currentTime) return
    let v: typeWatchHistry = {
      watchTime: new Date().getTime(),
      currentTime: dp.currentTime,
      duration: dp.duration,
      episode: episode.value,
      episode_name: videoInfo.value.vod_play_url[episode.value].name,
      vod_id: vod_id_.value,
      vod_img: videoInfo.value.vod_pic,
      vod_name: videoInfo.value.vod_name
    }
    lastHistry = v
    watchHistry.add(v)
  })
}

const itPage = ref(0)
const allCount = ref(1)
const pageShowCount = ref(30)
const selectVListBox = ref()
const selectVListBoxInnerBox = ref()
const baseNumber = ref(0)
const viewPageCount = ref(2)
const itScrolPage=ref(0)

const duration = 500
const cubicBezierNumber = useTransition(baseNumber, {
  duration,
  transition: [0.75, 0, 0.25, 1]
})

watch(
  () => cubicBezierNumber.value,
  () => {
    selectVListBox.value.setScrollLeft(cubicBezierNumber.value)
  }
)
function changePage(page: number) {
  let width = selectVListBoxInnerBox.value.clientWidth
  if (page < 0 || page > viewPageCount.value - 1) return
  itScrolPage.value = page
  baseNumber.value = page * width
}

const { width, height } = useElementSize(selectVListBoxInnerBox)
watchEffect(() => {
  if (width.value > 0) {
    let width_ = selectVListBoxInnerBox.value.clientWidth
    viewPageCount.value = Math.ceil(selectVListBox.value.wrapRef.scrollWidth / width_)
  }
})
const selectKey = ref('1')
function handleSelect(key: string, keyPath: string[]) {
  selectKey.value = keyPath[0]
}

const showInfo = ref(false)

window.addEventListener('beforeunload', e => {
  // window.navigator.sendBeacon(`https://fc-mp-d55e8f18-e485-4a28-a1b6-74998af468fc.next.bspapp.com/newVideoInfo/upVideoHistry`, JSON.stringify({ a: 123 }))
  video.upVideoHistry(lastHistry)
  // e.preventDefault();
})
</script>

<template>
  <div class="valueBox">
    <headerBar :aways-bg="true" class="headerBar"></headerBar>
    <div class="showPage">
      <div class="showPage-innerBox">
        <div class="playerBox">
          <div class="playerBox-videoBox">
            <div id="video"></div>
          </div>
          <div class="playerBox-list">
            <div class="playerBox-box" style="overflow: hidden">
              <div class="playerBox-box-info" :class="{ 'playerBox-box-infoShow': showInfo }" style="padding: 0 10px">
                <div class="playerBox-box-info-header">
                  <div>简介</div>
                  <el-icon style="cursor: pointer" @click="showInfo = false"><CloseBold /></el-icon>
                </div>
                <div class="playerBox-box-info-body">
                  <p>
                    {{ videoInfo?.vod_content.replace(/<(\S*?)[^>]*>.*?|<.*? \/>|#/g, '') }}
                  </p>
                </div>
              </div>
              <div class="playerBox-box-title">
                <p class="playerBox-list-title">{{ videoInfo?.vod_name }}</p>
                <div class="playerBox-list-infoBox" v-if="videoInfo?.vod_class">
                  <div>
                    <template v-for="vc in videoInfo.vod_class.split(',').slice(0, 3)" :key="vc">
                      <span>
                        {{ vc }}
                      </span>
                      <span class="playerBox-list-g">|</span>
                    </template>
                    <span>{{ videoInfo.vod_year }}</span>
                  </div>
                  <div @click="showInfo = true">
                    简介<el-icon><ArrowRightBold /></el-icon>
                  </div>
                </div>
                <el-menu class="el-menu-demo" mode="horizontal" :ellipsis="false" @select="handleSelect" :default-active="selectKey">
                  <el-menu-item index="1">选集</el-menu-item>
                  <el-menu-item index="2">评论</el-menu-item>
                </el-menu>
              </div>
              <div class="playerBox-box-page" v-show="selectKey == '1'">
                <div class="selectVListBox" :class="{ 'selectVListBox-noShow': Math.ceil(allCount / pageShowCount) <= 1 }">
                  <el-icon class="selectVListBox-btn" :class="{ 'selectVListBox-btnNo': itScrolPage == 0, 'selectVListBox-btnHide': viewPageCount == 1 }" @click="changePage(itScrolPage - 1)"><ArrowLeftBold /></el-icon>
                  <el-scrollbar ref="selectVListBox">
                    <div class="selectVListBox-itemBox" ref="selectVListBoxInnerBox">
                      <div @click="itPage = ceil - 1" class="selectVListBox-item" :class="{ 'selectVListBox-item-It': itPage == ceil - 1 }" v-for="ceil in Math.ceil(allCount / pageShowCount)" :key="ceil">{{ (ceil - 1) * pageShowCount + 1 }}-{{ Math.min(allCount, ceil * pageShowCount) }}</div>
                    </div>
                  </el-scrollbar>
                  <el-icon class="selectVListBox-btn" :class="{ 'selectVListBox-btnNo': itScrolPage == viewPageCount - 1, 'selectVListBox-btnHide': viewPageCount == 1 }" @click="changePage(itScrolPage + 1)"><ArrowRightBold /></el-icon>
                </div>
                <div class="selectBox">
                  <router-link class="selectBox-item" :class="{ 'selectBox-itemIt': episode == itPage * 30 + index }" :to="`/play/${vod_id_}?episode=${itPage * 30 + index}`" v-for="(u, index) in videoInfo?.vod_play_url.slice(itPage * 30, (itPage + 1) * 30)" :key="index">
                    <div>{{ u.name }}</div>
                  </router-link>
                </div>
              </div>
              <div v-show="selectKey == '2'" class="comment">
                <commentVue :vod_id="vod_id_"></commentVue>
              </div>
            </div>
          </div>
        </div>
        <showVideoListBox :video-list="videoPushList" name="为你推荐"></showVideoListBox>
        <footBar></footBar>
      </div>
    </div>
  </div>
</template>
<style lang="less">
.xgplayer .xgplayer-progress-played {
  background: linear-gradient(-90deg, rgb(3, 200, 212) 0%, rgb(1, 206, 205) 100%);
}

.xgplayer .xgplayer-drag {
  background: rgb(3, 200, 212);
}
.xgplayer .xg-options-list li.selected {
  color: rgb(3, 200, 212);
}
.xgplayer .xg-options-list li:hover,
.xgplayer .xg-options-list li.selected {
  color: rgb(3, 200, 212);
}

.xgplayer .xgplayer-progress .xgplayer-progress-btn {
  background: rgba(3, 200, 212, 0.304093);
  border: 0.5px solid rgba(3, 200, 212, 0.056545);
  box-shadow: 0 0 1px rgba(3, 200, 212, 0.304093);
}
</style>
<style scoped lang="less">
.comment {
  height: calc(100% - 130px);
}
.el-menu--horizontal {
  --el-menu-border-color: #333;
}
.selectBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin: 10px 20px;

  &-item {
    background: rgb(50, 50, 56);
    padding: 5px;
    margin-right: 20px;
    margin-bottom: 10px;
    width: calc(50% - 10px);
    text-align: center;
    border-radius: 5px;
    cursor: pointer;
    color: #aaa;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;

    &:nth-child(2n) {
      margin-right: 0;
    }

    &:hover {
      color: #eee;
      background: rgb(62, 62, 70);
    }
  }

  &-itemIt {
    color: #fff;
    // filter: drop-shadow(0 0 5px rgba(255, 255, 255, 0.5));
    background: rgba(1, 206, 205, 0.7);
    &:hover {
      background: rgba(1, 206, 205, 1);
    }
  }
}
.selectVListBox {
  display: flex;
  align-items: center;
  padding: 10px 0px 0;

  &-noShow {
    opacity: 0;
    margin-top: -25px;
  }

  &-btn {
    cursor: pointer;
    font-size: 15px;
    color: #fff;
    margin: 0 5px;
    opacity: 1;
  }
  &-btnNo {
    color: #888;
  }
  &-btnHide {
    opacity: 0;
    cursor: unset;
  }

  &-itemBox {
    display: flex;
  }

  &-item {
    flex-shrink: 0;
    color: #888;
    margin-right: 10px;
    font-weight: bolder;
    font-size: 15px;
    cursor: pointer;
    &:hover {
      color: #bbb;
    }

    &-It {
      color: #eee;
    }
  }
}
.playerBox {
  --bg-color: rgba(0, 0, 0, 0);
  --el-menu-hover-bg-color: rgba(0, 0, 0, 0);
  --el-menu-active-color: #fff;
  --el-menu-hover-text-color: #fff;
  --el-menu-text-color: #888;

  display: flex;
  position: relative;
  width: 100%;
  margin-bottom: 40px;
  border-radius: 0 20px 20px 0;
  // overflow: hidden;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);

  .el-menu {
    margin-top: 10px !important;
    height: 40px;

    .el-menu-item {
      width: 50%;
      &.is-active {
        border-bottom: 2px solid #888;
      }
    }
  }

  &-box {
    position: absolute;
    width: 100%;
    height: 100%;

    &-info {
      position: absolute;
      left: 100%;
      top: 0;
      width: 100%;
      height: 100%;
      background: #f00;
      z-index: 2;
      transition: 0.3s;
      background: rgb(30, 30, 36);

      &-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 20px 10px;
        font-size: 20px;
        border-bottom: 1px solid #333;
        color: #aaa;
      }

      &-body {
        padding: 20px 10px;
      }
    }
    &-infoShow {
      left: 0;
      transition: 0.3s;
    }

    &-title {
      padding: 20px 20px 0;
      // background: rgb(30, 30, 36);
      z-index: 1;
      height: 130px;
    }
    &-page {
      height: calc(100% - 130px);
      position: absolute;
      top: 0;
      margin-top: 130px;
      overflow-y: auto;
      overflow-x: hidden;
      width: 100%;

      &::-webkit-scrollbar {
        width: 3px;
      }
      // 滚动条轨道
      &::-webkit-scrollbar-track {
        background: rgba(0, 0, 0, 0);
        border-radius: 2px;
      }

      &::-webkit-scrollbar-thumb {
        background: rgba(255, 255, 255, 0);
        border-radius: 10px;
      }

      &:hover {
        &::-webkit-scrollbar-thumb {
          background: rgba(255, 255, 255, 0.2);
        }
      }
    }
  }

  &-list {
    min-width: 285px;
    width: 20%;
    background: rgb(30, 30, 36);
    font-size: 14px;
    position: relative;
    border-radius: 0 10px 10px 0;

    .el-menu-demo {
      margin: 0 -20px;
    }

    &-infoBox {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-top: 10px;
      color: #ccc;

      * {
        flex-shrink: 0;
      }

      > div:first-child {
        display: flex;
        align-items: center;
        width: 70%;
      }
      > div:last-child {
        cursor: pointer;
        color: #888;
      }
    }

    > p {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    &-title {
      font-size: 24px;
      font-weight: 700;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      position: relative;
    }

    &-g {
      padding: 0 5px;
    }
  }
  .playerBox-videoBox {
    background: rgb(30, 30, 36);
    position: relative;
    background-color: #000;
    width: 80%;
    padding-top: calc(80% * 0.5625);
    min-width: 725px;
    min-height: 407.8125px;
    max-width: 1897px;
    max-height: 1067.0625px;
    // height: calc(56.25vw - 269.4375px);

    #video {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
    }
  }
}
.valueBox {
  display: flex;
  position: relative;

  .headerBar {
    position: fixed;
    top: 0;
    // left: 0;
    width: 100%;
    z-index: 999;
    min-width: 1100px;
    max-width: 2376px;
    margin: 0 auto;
  }

  .showPage {
    width: 100%;
    color: #eee;

    &-innerBox {
      min-width: 1100px;
      margin-top: 70px;
      padding: 30px;
      padding-right: 30px;
      padding-top: 10px;
    }
  }
}

.router-link-active {
  text-decoration: none;
}

a {
  text-decoration: none;
}
</style>
